import { asyncRoutes, constantRoutes } from '@/router'
import {getNewRoutes, getRoutes} from '@/api/system/role'
import Layout from '@/layout'
import Layouts from '@/layouts'
import BaqsjLayouts from '@/baqsjLayouts'
// import sysuserindex from '@/views/sysuser/index'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Use names to determine if the current user has permission
 * @param names
 * @param route
 */
function hasPathPermission(paths, route) {
  if (route.path) {
    return paths.some(path => route.path === path.path)
  } else {
    return true
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
    // console.log(item);
    const menu = {
      path: item.path,
      // hidden: item.visible !== '0',
      hidden: false,
      children: [],
      name: item.menuName,
      mid: item.mid,
      meta: {
        title: item.title,
        icon: item.icon,
        activeMenu: item.activePath,
        noCache: true
      }
    }

    // console.log("component",item.component)

    if (item.component === 'Layout') {
      menu.component = BaqsjLayouts
    } else if (item.component === 'Layouts') {
      menu.component = Layouts
    } else if (item.component === 'BaqsjLayouts') {
      menu.component = BaqsjLayouts
    } else {
      menu.component = loadView(item.component)
    }
    if (item.children) {
      generaMenu(menu.children, item.children)
    }

    // console.log("组装后的路由",menu)

    routes.push(menu)
  })
  // console.log("组装后的路由",routes)
}

export function generaModMenu(routes, data, mid) {
  data.forEach(item => {
    console.log(item)
    // console.log(mid);
    if (item.mid === mid) {
      const menu = {
        path: item.path,
        hidden: item.visible !== '0',
        children: [],
        name: item.menuName,
        meta: {
          title: item.title,
          icon: item.icon,
          activeMenu: item.activePath,
          noCache: true
        }
      }
      if (item.component === 'Layout') {
        menu.component = Layout
      } else if (item.component === 'Layouts') {
        menu.component = Layouts
      } else if (item.component === 'BaqsjLayouts') {
        menu.component = BaqsjLayouts
      } else {
        menu.component = loadView(item.component)
      }
      if (item.children) {
        generaModMenu(menu.children, item.children, mid)
      }
      routes.push(menu)
    }
    console.log(routes)
  })
}

export const loadView = view => {
  // 路由懒加载
  return resolve => require(['@/views' + view], resolve)
  // return () => import(`@/views${view}`)
}


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param components
 */
export function filterAsyncPathRoutes(routes, paths) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPathPermission(paths, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncPathRoutes(tmp.children, paths)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, menuList) {
    return new Promise(resolve => {
      const loadMenuData = []

      const allMenuData = menuList

      allMenuData.forEach(item=>{
        item.path = item.menuRoute
        item.component = item.note
        item.hidden = false;
        item.menuName = item.menuDisp
        item.mid = item.sysModule
        item.title = item.menuDisp
        item.icon = item.menuLogo
        item.activeMenu = ""
        item.noCache = true
      })

      const parentMenu = allMenuData.filter(item=>item.menuType==='D')
      const childMenu = allMenuData.filter(item=>item.menuType==='F')

      const _parentMenu = parentMenu.map(item=>{
        return {
          ...item,
          children:childMenu.filter(child=>Number(child.parentMenuID)===item.id)
        }
      })

      // console.log("树形菜单",_parentMenu)

      const _xjsxxmMenu = _parentMenu.filter(item=>item.sysModule === "xjsxxm")
      const _systemMenu = _parentMenu.filter(item=>item.sysModule === "system")
      const rootRoute = [
        {
          component: "Layouts",
          path: "/newUpms",
          hidden:false,
          menuName:"newUpms",
          mid:"system",
          title:'系统模块',
          icon:'example',
          activeMenu:"",
          noCache:true,
          children:_systemMenu,
        },
        {
          component: "BaqsjLayouts",
          path: "/xjsxxm",
          hidden:false,
          menuName:"Xjsxxm",
          mid:"xjsxxm",
          title:'新技术管理平台',
          icon:'example',
          activeMenu:"",
          noCache:true,
          children:_xjsxxmMenu,
        },
      ]

      // console.log("55sfd",_xjsxxmMenu,_systemMenu)

      Object.assign(loadMenuData, rootRoute)
      generaMenu(asyncRoutes, loadMenuData)
      asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', asyncRoutes)
      console.log("真实路由",asyncRoutes)
      resolve(asyncRoutes)


      /*getNewRoutes({"pagesize":0}).then(res=>{
        const allMenuData = res.records;

        allMenuData.forEach(item=>{
          item.path = item.menuRoute
          item.component = item.note
          item.hidden = false;
          item.menuName = item.menuDisp
          item.mid = item.sysModule
          item.title = item.menuDisp
          item.icon = item.menuLogo
          item.activeMenu = ""
          item.noCache = true
        })

        const parentMenu = allMenuData.filter(item=>item.menuType==='D')
        const childMenu = allMenuData.filter(item=>item.menuType==='F')

        const _parentMenu = parentMenu.map(item=>{
          return {
            ...item,
            children:childMenu.filter(child=>Number(child.parentMenuID)===item.id)
          }
        })

        // console.log("树形菜单",_parentMenu)

        const _xjsxxmMenu = _parentMenu.filter(item=>item.sysModule === "xjsxxm")
        const _systemMenu = _parentMenu.filter(item=>item.sysModule === "system")
        const rootRoute = [
          {
            component: "Layouts",
            path: "/newUpms",
            hidden:false,
            menuName:"newUpms",
            mid:"system",
            title:'系统模块',
            icon:'example',
            activeMenu:"",
            noCache:true,
            children:_systemMenu,
          },
          {
            component: "Layouts",
            path: "/xjsxxm",
            hidden:false,
            menuName:"Xjsxxm",
            mid:"xjsxxm",
            title:'新技术管理平台',
            icon:'example',
            activeMenu:"",
            noCache:true,
            children:_xjsxxmMenu,
          },
        ]

        // console.log("55sfd",_xjsxxmMenu,_systemMenu)

        Object.assign(loadMenuData, rootRoute)
        generaMenu(asyncRoutes, loadMenuData)
        asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', asyncRoutes)
        console.log(asyncRoutes)
        resolve(asyncRoutes)


      })*/

      /*getRoutes()
        .then(response => {
          // console.log(JSON.stringify(response));
          let data = response
          if (response.code !== 200) {
            this.$message({
              message: '菜单数据加载异常',
              type: 0
            })
          } else {
            data = response.data
            Object.assign(loadMenuData, data)

            generaMenu(asyncRoutes, loadMenuData)
            asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
            commit('SET_ROUTES', asyncRoutes)
            console.log(asyncRoutes)
            resolve(asyncRoutes)
          }
        })
        .catch(error => {
          console.log(error)
        })*/
    })
  },
  generateModRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const loadMenuData = []

      getRoutes()
        .then(response => {
          // console.log(JSON.stringify(response));
          let data = response
          if (response.code !== 200) {
            this.$message({
              message: '菜单数据加载异常',
              type: 0
            })
          } else {
            data = response.data
            Object.assign(loadMenuData, data)
            let newData = []
            loadMenuData.forEach(item => {
              if (item.mid === 'xjsxxm' && item.parentId == 0) {
                newData = item.children
              }
            })
            generaModMenu(asyncRoutes, newData, 'xjsxxm')
            asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
            commit('SET_ROUTES', asyncRoutes)
            console.log(asyncRoutes)
            resolve(asyncRoutes)
          }
        })
        .catch(error => {
          console.log(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
